package cn.ultrarisk.scadmin.manager.web.interceptor;

import cn.ultrarisk.scadmin.manager.biz.user.entity.Admin;
import cn.ultrarisk.scadmin.manager.biz.user.util.SessionUtil;
import cn.ultrarisk.scadmin.manager.util.StringUtil;
import cn.ultrarisk.scadmin.manager.web.controller.LoginController;
import cn.ultrarisk.scadmin.manager.web.controller.LogoutController;
import cn.ultrarisk.scadmin.manager.web.controller.log.GatherLogController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * AuthenticationInterceptor
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/4/17
 * @since V1.0
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> handlerBeanClass = handlerMethod.getBean().getClass();
        if (handlerBeanClass == LoginController.class || handlerBeanClass == LogoutController.class || handlerBeanClass == GatherLogController.class) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("account".equals(cookie.getName())) {
                    String account = cookie.getValue();
                    if (StringUtil.isEmpty(account)) {
                        return false;
                    }
                    Admin admin = SessionUtil.getAdmin();
                    if (admin != null && admin.getAccount().equals(account)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
